package jxau.jwgl.web.controller;

import jxau.jwgl.commons.WebData;
import jxau.jwgl.commons.entity.Evaluation;
import jxau.jwgl.commons.entity.EvaluationTeach;
import jxau.jwgl.commons.entity.User;
import jxau.jwgl.service.EvaluationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.List;

/**
 * EvaluationController
 *
 * @author LongShu 2017/06/09
 */
@RestController
@RequestMapping("/evaluation")
public class EvaluationController extends BaseController {

    @Autowired
    private EvaluationService evaluationService;

    @GetMapping("evaluationList/{semester}")
    public Object evaluationList(@PathVariable String semester,
                                 @SessionAttribute(name = UserController.SESSION_USER_KEY, required = false) User loginUser) {
        if (loginUser == null) {
            return WebData.newError("请先登录!");
        }
        if (StringUtils.isBlank(semester)) {
            return WebData.newError("学期不能为空!");
        }

        List<EvaluationTeach> evaluationTeachList = evaluationService.evaluationList(loginUser.getUsername(), semester);
        return WebData.newObj(evaluationTeachList);
    }

    @PostMapping("submitEvaluation")
    public Object submitEvaluation(@RequestBody Evaluation evaluation,
                                   @SessionAttribute(name = UserController.SESSION_USER_KEY, required = false) User loginUser) {
        if (loginUser == null) {
            return WebData.newError("请先登录!");
        }

        // 防止重复提交后台任务
        if (evaluationService.isEvaluating(loginUser.getUsername(), evaluation.getSemester())) {
            return WebData.newError("评教任务进行中,请稍后再试!");
        }

        int count = evaluationService.submitEvaluation(loginUser.getUsername(), evaluation);
        return WebData.newMsg("评教任务提交成功!", count);
    }

}
